package com.link2room.quintesson.facade.impl;

import com.link2room.common.constant.BaseConstant;
import com.link2room.common.constant.DefaultValue;
import com.link2room.common.service.ICommonService;
import com.link2room.common.util.DateUtil;
import com.link2room.common.util.HotelUtil;
import com.link2room.common.util.JacksonUtil;
import com.link2room.enums.exception.QuintessonSysExceptionEnum;
import com.link2room.jetfire.constant.ReservationConstant;
import com.link2room.jetfire.dto.param.base.ReservationParamDto;
import com.link2room.jetfire.dto.param.inside.ReservationPayInsideParamDto;
import com.link2room.jetfire.dto.result.base.ReservationBaseDto;
import com.link2room.jetfire.dto.result.base.ReservationDto;
import com.link2room.jetfire.dto.result.base.ReservationPriceDto;
import com.link2room.optimus.constant.BaseRateplanConstant;
import com.link2room.optimus.dto.param.inside.BookStockInsideParamDto;
import com.link2room.optimus.dto.result.base.L2REverydayPriceAndStockDto;
import com.link2room.optimus.dto.result.base.BookStockDto;
import com.link2room.quintesson.entity.TaobaoXrate;
import com.link2room.quintesson.entity.TaobaoXroomtype;
import com.link2room.quintesson.exception.TaobaoException;
import com.link2room.quintesson.facade.ITaobaoReservationFacadeService;
import com.link2room.quintesson.feign.jetfire.ReservationsFeignService;
import com.link2room.quintesson.feign.optimus.MarketingDetailFeignService;
import com.link2room.trailbreaker.constant.Pay;
import org.dom4j.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

/**
 * Created by sss on 2017/5/3.
 */
@Component("taobaoReservationFacadeService")
public class TaobaoReservationFacadeServiceImpl implements ITaobaoReservationFacadeService {
    @Resource
    private ICommonService commonService;
    @Autowired
    private MarketingDetailFeignService marketingDetailFeignService;
    @Autowired
    private ReservationsFeignService reservationsFeignService;

    @Override
    public String resolveTaobaoValidateRQ(Element rootElement)throws Exception{
        //集团代码
        String lhotelGroupCode="";
        //酒店代码
        String lhotelCode="";
        //房型代码
        String rmtype="";
        //到店时间
        String checkIn="";
        //离店时间
        String checkOut="";
        //房数
        Integer rmNum=0;
        //订单类型
        String paymentType="";
        //卖家价格计划代码
        String hotelRpCode="";

        if(rootElement.element("HotelId")!=null){
            lhotelCode=rootElement.element("HotelId").getStringValue();
            String[] hotelOutCode=rootElement.element("HotelId").getStringValue().split("_");
            lhotelGroupCode=hotelOutCode[0];
        }

        if(rootElement.element("RoomTypeId")!=null){
            rmtype=rootElement.element("RoomTypeId").getStringValue();
        }

        if(rootElement.element("RatePlanCode")!=null){
            hotelRpCode=rootElement.element("RatePlanCode").getStringValue();
        }

        if(rootElement.element("CheckIn")!=null){
            checkIn=rootElement.element("CheckIn").getStringValue();
        }

        if(rootElement.element("CheckOut")!=null){
            checkOut=rootElement.element("CheckOut").getStringValue();
        }

        if(rootElement.element("RoomNum")!=null){
            rmNum=Integer.parseInt(rootElement.element("RoomNum").getStringValue());
        }
        TaobaoXrate queryRate=new TaobaoXrate();
        queryRate.setLhotelGroupCode(lhotelGroupCode);
        queryRate.setLhotelCode(lhotelCode);
        queryRate.setRmtype(rmtype);
        queryRate.setHotelRpCode(hotelRpCode);
        TaobaoXrate taobaoXrate=commonService.findOneEQ(TaobaoXrate.class,queryRate);
        if(taobaoXrate!=null){
            String mcdCode= taobaoXrate.getMcdCode();
            BookStockInsideParamDto bookStockInsideParamDto=new BookStockInsideParamDto();
            bookStockInsideParamDto.setLhotelGroupCode(lhotelGroupCode);
            bookStockInsideParamDto.setLhotelCode(lhotelCode);
            bookStockInsideParamDto.setCheckInDatetime(checkIn);
            bookStockInsideParamDto.setCheckOutDatetime(checkOut);
            bookStockInsideParamDto.setRmNum(rmNum);
            bookStockInsideParamDto.setMcdCode(mcdCode);
            bookStockInsideParamDto.setPbChannel(BaseConstant.PbChannelConstant.TAOBAO);
            bookStockInsideParamDto.setIsUsePoint(DefaultValue.F);
            BookStockDto bookStockDto = marketingDetailFeignService.bookStocks(bookStockInsideParamDto.paramToMap()).getResultInfo();
            if(bookStockDto==null){
                throw new TaobaoException(QuintessonSysExceptionEnum.TAOBAO_OTHER_EXCEPTION);
            }else {
                List<Map<String,String>> inventoryPriceList=new ArrayList<>();
                for(L2REverydayPriceAndStockDto priceAndStock:bookStockDto.getL2REverydayPriceAndStockDtoList()){
                    Map<String,String> inventoryPrice=new HashMap<>();
                    inventoryPrice.put("date", DateUtil.format(priceAndStock.getRsvDate(), DateUtil.webFormat));
                    inventoryPrice.put("price", priceAndStock.getL2REverydayPriceDto().getCurrentPrice().multiply(new BigDecimal(100)).setScale(0).toString());
                    if(priceAndStock.getL2REverydayStockDto()!=null){
                        inventoryPrice.put("quota", priceAndStock.getL2REverydayStockDto().getSaleNum().toString());
                    }
                    inventoryPriceList.add(inventoryPrice);
                }
                String inventoryPrice=JacksonUtil.beanToJson(inventoryPriceList);
                if(DefaultValue.T.equals(bookStockDto.getIsBookable())){
                    return inventoryPrice;
                }else {
                    if(DefaultValue.T.equals(bookStockDto.getIsFull())){
                        throw new TaobaoException(QuintessonSysExceptionEnum.TAOBAO_ROOM_FULL);
                    }else {
                        throw new TaobaoException(QuintessonSysExceptionEnum.TAOBAO_ROOM_LESS,null,inventoryPrice);
                    }
                }
            }
        }else {
            throw new TaobaoException(QuintessonSysExceptionEnum.TAOBAO_OTHER_EXCEPTION,QuintessonSysExceptionEnum.TAOBAO_RATE_NOT_EXIT.getMsg());
        }
    }

    /**
     * 淘宝下单请求解析组装
     * @param rootElement
     * @throws Exception
     */
    @Override
    public String resolveTaobaoBookRQ(Element rootElement) throws Exception{
        //淘旅订单号
        String taoBaoOrderId="";
        //集团代码
        String lhotelGroupCode="";
        //酒店代码
        String lhotelCode="";
        //房型
        String rmtype="";
        //到店时间
        String checkIn="";
        //离店时间
        String checkOut="";
        //最早到店时间
        String earliestArriveTime="";
        //最晚到店时间
        String latestArriveTime="";
        //房数
        Integer roomNum=0;
        //订单总价
        String totalPrice="";
        //卖价优惠金额
        String totalSellerPromotion="";
        //预订人
        String rsvMan="";
        //手机号
        String mobile="";
        //订单类型
        String paymentType="";
        //宾客姓名
        String name="";
        //房间序号
        String roomPos="";
        //备注
        String remark="";
        //入住人数
        Integer adult=1;

        //卖家自己价格计划代码
        String hotelRpCode="";
        //卖家自己房型代码
        String outerRid="";

        String voucherTid="";

        String voucherId="";

        String voucherNum="";

        String alipayTradeNo="";

        if(rootElement.element("TaoBaoOrderId")!=null){
            taoBaoOrderId=rootElement.element("TaoBaoOrderId").getStringValue();
        }

        if(rootElement.element("HotelId")!=null){
            lhotelCode=rootElement.element("HotelId").getStringValue();
            String[] hotelOutCode=rootElement.element("HotelId").getStringValue().split("_");
            lhotelGroupCode=hotelOutCode[0];
        }

        if(rootElement.element("RoomTypeId")!=null){
            rmtype=rootElement.element("RoomTypeId").getStringValue();
        }

        if(rootElement.element("RatePlanCode")!=null){
            hotelRpCode=rootElement.element("RatePlanCode").getStringValue();
        }

        if(rootElement.element("CheckIn")!=null){
            checkIn=rootElement.element("CheckIn").getStringValue()+" 18:00:00";
        }

        if(rootElement.element("CheckOut")!=null){
            checkOut=rootElement.element("CheckOut").getStringValue()+" 12:00:00";
        }

        if(rootElement.element("EarliestArriveTime")!=null){
            earliestArriveTime=rootElement.element("EarliestArriveTime").getStringValue();
        }

        if(rootElement.element("LatestArriveTime")!=null){
            latestArriveTime=rootElement.element("LatestArriveTime").getStringValue();
        }

        if(rootElement.element("RoomNum")!=null){
            roomNum=Integer.parseInt(rootElement.element("RoomNum").getStringValue());
        }
        if(rootElement.element("Occupancy")!=null){
            adult=Integer.parseInt(rootElement.element("Occupancy").getStringValue());
        }

        if(rootElement.element("TotalPrice")!=null){
            totalPrice=rootElement.element("TotalPrice").getStringValue();
        }
        if(rootElement.element("TotalSellerPromotion")!=null){
            totalSellerPromotion=rootElement.element("TotalSellerPromotion").getStringValue();
        }

        if(rootElement.element("ContactName")!=null){
            rsvMan=rootElement.element("ContactName").getStringValue();
        }

        if(rootElement.element("ContactTel")!=null){
            mobile=rootElement.element("ContactTel").getStringValue();
        }

        if(rootElement.element("PaymentType")!=null){
            paymentType=rootElement.element("PaymentType").getStringValue();
        }

        if(rootElement.element("Comment")!=null){
            remark=new String(rootElement.element("Comment").getStringValue().getBytes("utf-8"), "utf-8");
        }
        if(rootElement.element("VoucherInfos")!=null){
            Iterator<Element> secIt = rootElement.element("VoucherInfos").elementIterator();
            while(secIt.hasNext()){
                Element secElement=secIt.next();
                if(secElement.element("VoucherTid")!=null){
                    voucherTid=secElement.element("VoucherTid").getStringValue();
                }
                if(secElement.element("VoucherId")!=null){
                    voucherId=secElement.element("VoucherId").getStringValue();
                }
                if(secElement.element("VoucherNum")!=null){
                    voucherNum=secElement.element("VoucherNum").getStringValue();
                }
            }
        }

        List<ReservationPriceDto> reservationPriceList=new ArrayList<ReservationPriceDto>();
        if(rootElement.element("DailyInfos")!=null){
            Iterator<Element> secIt = rootElement.element("DailyInfos").elementIterator();
            int i=0;
            while(secIt.hasNext()){
                Element secElement=secIt.next();
                ReservationPriceDto reservationPrice=new ReservationPriceDto();
                if(secElement.element("Day")!=null){
                    reservationPrice.setResDate(DateUtil.parseDateWevFormat(secElement.element("Day").getStringValue()));
                }
                if(secElement.element("Price")!=null){
                    reservationPrice.setAmountSale(new BigDecimal(secElement.element("Price").getStringValue()).divide(new BigDecimal(100)));
                }
                reservationPriceList.add(reservationPrice);
            }
        }

        if(rootElement.element("OrderGuests")!=null){
            Iterator<Element> secIt = rootElement.element("OrderGuests").elementIterator();
            int i=0;
            while(secIt.hasNext()){
                Element secElement=secIt.next();
                Iterator<Element> thirIt=secElement.elementIterator();
                while(thirIt.hasNext()){
                    Element thirElement=thirIt.next();
                    if("Name".equals(thirElement.getName())){
                        if(i==0){
                            name=new String(thirElement.getStringValue().getBytes("utf-8"), "utf-8");
                        }else{
                            name+=","+new String(thirElement.getStringValue().getBytes("utf-8"), "utf-8");
                        }
                    }
                    if("RoomPos".equals(thirElement.getName())){
                        if(i==0){
                            roomPos=thirElement.getStringValue();
                        }else{
                            roomPos+=","+thirElement.getStringValue();
                        }
                    }
                }
                i++;
            }
        }
        if(rootElement.element("AlipayTradeNo")!=null){
            alipayTradeNo=new String(rootElement.element("AlipayTradeNo").getStringValue().getBytes("utf-8"), "utf-8");
        }

        TaobaoXrate queryRate=new TaobaoXrate();
        queryRate.setLhotelGroupCode(lhotelGroupCode);
        queryRate.setLhotelCode(lhotelCode);
        queryRate.setRmtype(rmtype);
        queryRate.setHotelRpCode(hotelRpCode);
        TaobaoXrate taobaoXrate=commonService.findOneEQ(TaobaoXrate.class,queryRate);
        TaobaoXroomtype queryRmtype=new TaobaoXroomtype();
        queryRmtype.setLhotelGroupCode(lhotelGroupCode);
        queryRmtype.setLhotelCode(lhotelCode);
        queryRmtype.setRmtype(rmtype);
        TaobaoXroomtype taobaoXroomtype=commonService.findOneEQ(TaobaoXroomtype.class,queryRmtype);
        if(taobaoXrate!=null){
            String resType=null;
            if("1".equals(paymentType)){
                resType= BaseRateplanConstant.RESTYPE.TAOBAO_PRE;
            }else if("6".equals(paymentType)){
                resType=BaseRateplanConstant.RESTYPE.TAOBAO_CREDIT;
            }
            ReservationBaseDto reservationBaseDto=new ReservationBaseDto();
            reservationBaseDto.setLhotelGroupCode(lhotelGroupCode);
            reservationBaseDto.setLhotelCode(lhotelCode);
            reservationBaseDto.setPbChannel(BaseConstant.PbChannelConstant.TAOBAO);
            reservationBaseDto.setAdult(adult);
            reservationBaseDto.setMcCode(taobaoXrate.getMcCode());
            reservationBaseDto.setRmtype(rmtype);
            reservationBaseDto.setAmount(new BigDecimal(totalPrice).divide(new BigDecimal(100)));
            reservationBaseDto.setArrtime(checkIn);
            reservationBaseDto.setDeptime(checkOut);
            reservationBaseDto.setTerminalNo(taoBaoOrderId);
            reservationBaseDto.setIsUsePoint(DefaultValue.F);
            reservationBaseDto.setMcdCode(taobaoXrate.getMcdCode());
            reservationBaseDto.setMcdName(taobaoXrate.getName());
            reservationBaseDto.setResType(resType);
            reservationBaseDto.setRoomNum(roomNum);
            reservationBaseDto.setRmtypeName(taobaoXroomtype.getName());
            reservationBaseDto.setHotelName(HotelUtil.getRedisHotelName(lhotelCode));
            reservationBaseDto.setRsvMan(rsvMan);
            reservationBaseDto.setRsvMobile(mobile);
            ReservationParamDto reservationParamDto=new ReservationParamDto();
            reservationParamDto.setLhotelGroupCode(lhotelGroupCode);
            reservationParamDto.setReservationBase(reservationBaseDto);
            reservationParamDto.setReservationPriceDtos(reservationPriceList);
            ReservationBaseDto reservationBaseDtoNew=reservationsFeignService.createReservation(reservationParamDto).getResultInfo();
            if(BaseRateplanConstant.RESTYPE.TAOBAO_PRE.equals(resType)){
                ReservationPayInsideParamDto payParamDto = new ReservationPayInsideParamDto();
                payParamDto.setLhotelGroupCode(lhotelGroupCode);
                payParamDto.setLhotelCode(lhotelCode);
                payParamDto.setTaNo(alipayTradeNo);
                payParamDto.setPayChannel(Pay._Channel.ALIPAY);
                payParamDto.setPayType(Pay._Type.ALIPAY.ALI_ORDER_PRE_PAY);
                payParamDto.setAmount(new BigDecimal(totalPrice).divide(new BigDecimal(100)));
                payParamDto.setOrderNo(reservationBaseDtoNew.getL2RNo());
                payParamDto.setRemark("飞猪预付："+payParamDto.getAmount());
                payParamDto.setLimitOnce(DefaultValue.F);
                reservationsFeignService.payment(payParamDto);
            }
            return reservationBaseDtoNew.getL2RNo();
        }else {
            throw new TaobaoException(QuintessonSysExceptionEnum.TAOBAO_OTHER_EXCEPTION,QuintessonSysExceptionEnum.TAOBAO_RATE_NOT_EXIT.getMsg());
        }
    }


    /**
     * 淘宝取消订单请求解析组装
     * @param rootElement
     * @throws Exception
     */
    @Override
    public void resolveTaobaoCanceleRQ(Element rootElement) throws Exception{
        //集团代码
        String lhotelGroupCode="";
        //酒店代码
        String lhotelCode="";
        //联房订单号
        String l2rNo="";

        if(rootElement.element("HotelId")!=null){
            lhotelCode=rootElement.element("HotelId").getStringValue();
            String[] hotelOutCode=rootElement.element("HotelId").getStringValue().split("_");
            lhotelGroupCode=hotelOutCode[0];
        }

        if(rootElement.element("OrderId")!=null){
            l2rNo=rootElement.element("OrderId").getStringValue();
        }
        ReservationParamDto reservationParamDto=new ReservationParamDto();
        reservationParamDto.setLhotelGroupCode(lhotelGroupCode);
        reservationParamDto.setLhotelCode(lhotelCode);
        reservationParamDto.setL2rNo(l2rNo);
        reservationsFeignService.cancelReservation(reservationParamDto.paramToMap());
    }

    /**
     * 淘宝订单查询请求解析组装
     * @param rootElement
     * @throws Exception
     */
    @Override
    public ReservationDto resolveTaobaoQueryRQ(Element rootElement) throws Exception{
        //集团代码
        String lhotelGroupCode="";
        //酒店代码
        String lhotelCode="";
        //联房订单号
        String l2rNo="";
        //淘旅订单号
        String taobaoOrderId="";

        if(rootElement.element("HotelId")!=null){
            lhotelCode=rootElement.element("HotelId").getStringValue();
            String[] hotelOutCode=rootElement.element("HotelId").getStringValue().split("_");
            lhotelGroupCode=hotelOutCode[0];
        }

        if(rootElement.element("OrderId")!=null){
            l2rNo=rootElement.element("OrderId").getStringValue();
        }

        if(rootElement.element("TaoBaoOrderId")!=null){
            taobaoOrderId=rootElement.element("TaoBaoOrderId").getStringValue();
        }
        ReservationParamDto reservationParamDto=new ReservationParamDto();
        reservationParamDto.setLhotelGroupCode(lhotelGroupCode);
        reservationParamDto.setLhotelCode(lhotelCode);
        reservationParamDto.setL2rNo(l2rNo);
        reservationParamDto.setTerminalNo(taobaoOrderId);
        reservationParamDto.setResSta(ReservationConstant.RESSTA.R);
        ReservationDto reservation= reservationsFeignService.getReservation(reservationParamDto.paramToMap()).getResultInfo();
        return reservation;
    }
}
